package coder.nav.common;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;

import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Data
@Slf4j
public class R<T> implements Serializable {

    private Integer code;
    private String msg;
    private T data;

    public R() {
        this.code = 200;
    }

    public R(T data) {
        this.code = 200;
        this.data = data;
    }

    public R(Exception ex) {

        this.code = 500;
        this.msg = ex.getMessage();

        // 参数校验异常
        if("MethodArgumentNotValidException".equals(ex.getClass().getSimpleName())) {
            String[] array = ex.getMessage().split(";");
            if(array.length == 0) {
                return;
            }
            String message = array[array.length - 1];
            Pattern pattern = Pattern.compile("\\[(.*?)]");
            Matcher matcher = pattern.matcher(message);
            if(matcher.find()) {
                message = matcher.group(0);
                message = message.replace("[", "");
                message = message.replace("]", "");
                this.msg = message;
            }
        }

    }

}
